package com.easycarebn.main.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.timbacsi.main.MainActivity;
import com.timbacsi.main.R;

public class DownloadAttach extends AsyncTask<String, Integer, String> {
    private Activity activity;
    private String nameFile;
    private NotificationManager mNotifyManager;
    private NotificationCompat.Builder mBuilder;

    private int requestCode = 0;
    public static String urlDownload = "/EasyCareDownload/";

    public DownloadAttach(Activity activity, String nameFile, int requestCode) {
        super();
        this.activity = activity;
        this.nameFile = nameFile;
        this.requestCode = requestCode;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mNotifyManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);

        mBuilder = new NotificationCompat.Builder(activity);
        mBuilder.setContentTitle(String.format(activity.getResources().getString(R.string.laylaimk), nameFile))
                .setContentText(activity.getResources().getString(R.string.tien_trinh_tai_file))
                .setSmallIcon(R.drawable.ic_launcher);

        Intent intent = new Intent();
        PendingIntent i = PendingIntent.getActivity(activity, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(i);

        mBuilder.setProgress(0, 0, true);
        mNotifyManager.notify(requestCode, mBuilder.build());
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);

        // mBuilder.setProgress(100, progress[0], false);
        // mNotifyManager.notify(requestCode, mBuilder.build());

        if (progress[0] == 100) {
            Utils.showMessage(activity, String.format(activity.getResources().getString(R.string.tai_file_thanh_cong), nameFile));
            File myFile = new File(Environment.getExternalStorageDirectory() + urlDownload + nameFile);

            Intent intent = openFile(myFile);
            PendingIntent i = PendingIntent.getActivity(activity, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(i);

            mBuilder.setContentText(activity.getResources().getString(R.string.hoan_thanh)).setProgress(0, 0, false);
            mBuilder.build().flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
            mBuilder.setAutoCancel(true);
            mNotifyManager.notify(requestCode, mBuilder.build());
            // if (!MainActivity.isPause) {
            MainActivity.isPause = true;
            mNotifyManager.cancel(requestCode);
            activity.startActivity(intent);
            Log.d("mNotifyManager", "mNotifyManager");
            // }
        } else if (progress[0] == -101) {
            Utils.showMessage(activity, activity.getResources().getString(R.string.khong_co_ket_noi));

            Intent intent = new Intent();

            PendingIntent i = PendingIntent.getActivity(activity, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(i);

            mBuilder.setContentText(activity.getResources().getString(R.string.loi_file)).setProgress(0, 0, false);
            mBuilder.build().flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
            mBuilder.setAutoCancel(true);
            mNotifyManager.notify(requestCode, mBuilder.build());
        } else if (progress[0] == -102) {
            mNotifyManager.cancel(requestCode);
        }
    }

    public Intent openFile(File url) {
        Intent intent = null;
        try {
            // Create URI
            File file = url;
            Uri uri = Uri.fromFile(file);

            intent = new Intent(Intent.ACTION_VIEW);
            // Check what kind of file you are trying to open, by comparing the
            // url
            // with extensions.
            // When the if condition is matched, plugin sets the correct intent
            // (mime) type,
            // so Android knew what application to use to open the file
            if (url.toString().contains(".doc") || url.toString().contains(".docx")) {
                // Word document
                intent.setDataAndType(uri, "application/msword");
            } else if (url.toString().contains(".pdf")) {
                // PDF file
                intent.setDataAndType(uri, "application/pdf");
            } else if (url.toString().contains(".ppt") || url.toString().contains(".pptx")) {
                // Powerpoint file
                intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
            } else if (url.toString().contains(".xls") || url.toString().contains(".xlsx")) {
                // Excel file
                intent.setDataAndType(uri, "application/vnd.ms-excel");
            } else if (url.toString().contains(".zip") || url.toString().contains(".rar")) {
                // WAV audio file
                intent.setDataAndType(uri, "application/x-wav");
            } else if (url.toString().contains(".rtf")) {
                // RTF file
                intent.setDataAndType(uri, "application/rtf");
            } else if (url.toString().contains(".wav") || url.toString().contains(".mp3")) {
                // WAV audio file
                intent.setDataAndType(uri, "audio/x-wav");
            } else if (url.toString().contains(".gif")) {
                // GIF file
                intent.setDataAndType(uri, "image/gif");
            } else if (url.toString().contains(".jpg") || url.toString().contains(".jpeg") || url.toString().contains(".png")) {
                // JPG file
                intent.setDataAndType(uri, "image/jpeg");
            } else if (url.toString().contains(".txt")) {
                // Text file
                intent.setDataAndType(uri, "text/plain");
            } else if (url.toString().contains(".3gp") || url.toString().contains(".mpg") || url.toString().contains(".mpeg")
                    || url.toString().contains(".mpe") || url.toString().contains(".mp4") || url.toString().contains(".avi")) {
                // Video files
                intent.setDataAndType(uri, "video/*");
            } else {
                intent.setDataAndType(uri, "*/*");
            }

            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        } catch (Exception e) {

        }
        return intent;
    }

    @Override
    protected String doInBackground(String... sUrl) {
        try {
            URL url = new URL(sUrl[0]);
            URLConnection connection = url.openConnection();
            connection.connect();

            int fileLength = connection.getContentLength();

            // Check folder
            File folder = new File(Environment.getExternalStorageDirectory() + "/EasyCareDownload");
            if (!folder.exists()) {
                folder.mkdir();
            }

            // download the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + urlDownload + nameFile);
            File fileApk = new File(Environment.getExternalStorageDirectory() + urlDownload + nameFile);

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                if (fileApk.exists()) {
                    total += count;
                    // publishing the progress....
                    publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                } else {
                    publishProgress(-102);
                    break;
                }
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
            publishProgress(-101);
        }
        return null;
    }
}
